package org.jeecg.modules.iot.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MqttListenStart implements ApplicationListener<ContextRefreshedEvent> {
    @Value("${mqtt.username}")
    private String username;
    @Value("${mqtt.password}")
    private String password;
    private final MqttClientAPI mqttClientAPI;
    private final MqttCB mqttCB;

    @Autowired
    public MqttListenStart(MqttClientAPI mqttClientAPI, MqttCB mqttCB) {
        this.mqttClientAPI = mqttClientAPI;
        this.mqttCB = mqttCB;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        try {
            mqttClientAPI.setMqttClient(username, password, mqttCB);
            mqttClientAPI.subscribe("com/iot/init");
        } catch (MqttException e) {
            log.error(e.getMessage(), e);
        }
    }
}
